package tiruvury.InterviewPrep.DataStructures;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class MyHashtable<K, V>
{
	public class MyNode
	{
		K key;
		V value;

		public MyNode(K key, V value)
		{
			this.key = key;
			this.value = value;
		}

	}

	int size = 16;
	List<LinkedList<MyNode>> buckets = new ArrayList<LinkedList<MyNode>>(size);

	public MyHashtable()
	{
		for (int i = 0; i < this.size; i++)
		{
			buckets.add(new LinkedList<MyNode>());
		}
	}

	public void myPut(K key, V value)
	{
		/*
		 * SYNTAXERROR: PUT ONLY IF YOU DONT HAVE IT ALREADY - YOU MISSED
		 * THAT
		 */
		if (myGet(key) == null)
		{
			System.out.println("Key " + key.toString() + " not found. Adding it to the hashtable.");
			List<MyNode> list = getList(getBucket(key));
			list.add(new MyNode(key, value));
		}
		else
		{
			System.out.println("Key " + key.toString() + " ALREADY IN hashtable. No Op..");
		}
	}

	public V myGet(K key)
	{
		V valueToReturn = null;
		List<MyNode> list = getList(getBucket(key));

		Iterator<MyNode> itr = list.iterator();
		while (itr.hasNext())
		{
			MyNode node = itr.next();
			if (node.key == key)
			{
				valueToReturn = node.value;
				break;
			}
		}

		if (valueToReturn != null)
		{
			System.out.println("Key: " + key.toString() + " Value: " + valueToReturn.toString());
		}

		return valueToReturn;
	}

	private int getBucket(K key)
	{
		return (key.hashCode() % size);
	}

	private List<MyNode> getList(int bucket)
	{
		return buckets.get(bucket);
	}
}
